package com.xiaochun.hxhj;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.adapter.TestTableAdapter;
import com.myview.MyGraidView;
import com.util.DownUtil2;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class TestActivity extends BaseActivity {

    private WebView webview;
    private long lastClickTime;
    private int backPressedCounter;
    private MyGraidView gridview;
    private Button btn_play;
    private MediaPlayer mediaPlayer;
    private Button btn_down;
    private TextView tv_text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initListener() {
        btn_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new MyThread(2).start();

            }
        });
        btn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                play2();
            }
        });
    }

    class MyThread extends Thread {

        private int flag = 0;

        public MyThread() {
        }

        public MyThread(int flag) {
            this.flag = flag;
        }

        @Override
        public void run() {
            if (2 == flag) { // 复杂文件下载及存储到手机SD卡


//                new DownUtil("https://oss.bigchun.com/fastmemory/uploads/20200612/3db358824b16959e4a362bff7110d5c8.mp3","/storage/emulated/0/test_music/i_remember.mp3").start();
                new DownUtil2("https://oss.bigchun.com/fastmemory/uploads/20200612/3db358824b16959e4a362bff7110d5c8.mp3","i_remember.mp3",0).start();


            }
        }
    }

    private static final String PATH = Environment.getExternalStorageDirectory().getPath() + "/huixueji_music/";

    /**
     * 播放本地音乐
     */
    public void play() {
        mediaPlayer.reset();
//        String uri = PATH + "v1.mp3";
        String uri = "/storage/emulated/0/storage/emulated/0/huixueji_music/"+"v1.mp3";
        File file = new File(uri);
        if (file.exists()) {
            try {
                mediaPlayer.setDataSource(uri);//设置播放的数据源
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//设置音频流的类型，不是必须的
                /*mediaPlayer.prepare();//准备开始播放，prepare方法是native类型的，播放的逻辑是由c代码在新的线程里面执行的
                mediaPlayer.start();*/

                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {//准备完毕后调用
                        @Override
                        public void onPrepared(MediaPlayer mediaPlayer) {
                            mediaPlayer.start();//开始播放音乐
                        }
                    });
                    mediaPlayer.prepareAsync();//异步准备

            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "请检查是否有写SD卡权限", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
        }
    }
    public void play2() {
        mediaPlayer.reset();
        try{

            if (mediaPlayer.isPlaying()){
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer.setDataSource("/storage/emulated/0/test_music/i_remember.mp3");
                mediaPlayer.prepare();
            }else{
                mediaPlayer.setDataSource("/storage/emulated/0/test_music/i_remember.mp3");
                mediaPlayer.prepare();
            }

            mediaPlayer.start();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_test;
    }

    @Override
    protected void initView() {
        changeTitle("王冰寒");
//        saveNoticeList("name","王冰寒");
        List<String> lists = new ArrayList<>();
        lists.add("1");
        lists.add("2");
        lists.add("3");
        lists.add("4");
        lists.add("5");
        lists.add("6");
        lists.add("7");
        lists.add("8");
        lists.add("9");
        String name = getVoiceList("name");

        tv_text = findViewById(R.id.tv_text);
        btn_down = findViewById(R.id.btn_down);
        btn_play = findViewById(R.id.btn_play);
        mediaPlayer = new MediaPlayer();
        gridview = findViewById(R.id.gridview);
        TestTableAdapter adapter = new TestTableAdapter(context, lists);
        gridview.setAdapter(adapter);
//            showToast(name);
        webview = findViewById(R.id.webview);
        WebSettings webSettings = webview.getSettings(); //支持缩放，默认为true。
        webSettings.setUseWideViewPort(true); // 缩放至屏幕的大小 webSettings
        webSettings.setLoadWithOverviewMode(true); //设置默认编码
        webSettings.setDefaultTextEncodingName("utf-8"); ////设置自动加载图片
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setJavaScriptEnabled(true);// 设置可以运行JS脚本
        webSettings.setSupportZoom(false);// 用于设置webview放大
        webSettings.setBuiltInZoomControls(false);

        //支持js
        webSettings.setJavaScriptEnabled(true);
        //设置本地调用对象及其接口
        webview.addJavascriptInterface(new Waimairenjsobj(), "h5_android");
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //在这里执行你想调用的js函数

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
                super.onReceivedSslError(view, handler, error);
            }
        });

//        Log.e("公式url","https://"+url);
        webview.loadUrl("https://d-xiaojizhe.bigchun.com/dist/index.html");

    }


    @Override
    protected void initData() {

    }

    private final class Waimairenjsobj {
        // 打电话
        @JavascriptInterface
        public void reback() {
            Log.e("返回按钮", "进入返回按钮");
            finish();
        }

    }

    /**
     * 重写onKeyDown，当浏览网页，WebView可以后退时执行后退操作。
     * false 执行安卓返回方法即webview返回上一页 true 表示h5处理返回事件，android端不再处理
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            webview.evaluateJavascript("javascript:_Native_backListener()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    if ("false".equals(value) || "null".equals(value)) {
                        showToast("执行安卓返回方法");
                        goBack();
                    } else if ("true".equals(value)) {
                        // h5处理，客户端不做任何操作
                        showToast("h5处理，客户端不做任何操作");
                    }
                }
            });
        }
        return true;
    }

    private void goBack() {
        if (webview.canGoBack()) {
            webview.goBack();
        } else {
            TestActivity.this.finish();
           /* // 网页不可返回上一页，按两次退出
            long now = System.currentTimeMillis();
            long delta = now - lastClickTime;
            if (delta > 3 * 1000) {
                backPressedCounter = 0;
            }
            lastClickTime = now;
            backPressedCounter++;
            if (backPressedCounter == 1) {
//                mHandle.sendEmptyMessage(CLOSE_APP_TIP);
            } else if (backPressedCounter == 2) {
                TestActivity.this.finish();
            }*/
        }
    }


}
